package com.wrxdz.start.surfaceviewt.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.wrxdz.start.surfaceviewt.ApplicationUtil;
import com.wrxdz.start.surfaceviewt.R;
import com.wrxdz.start.surfaceviewt.surfview.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ClientActivity extends AppCompatActivity {
    public static final String TAG = "ClientActivity";
    @BindView(R.id.client_edit)
    EditText show;
    @BindView(R.id.client_connect)
    Button connect;
    @BindView(R.id.client_user_name)
    EditText user_name;
    private int[] selfPukes ;
    private int[] threePukes;
    private String[] userNames;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    show.setText((String) msg.obj);
                    break;
                case 1:
                    Toast.makeText(ClientActivity.this, "连接超时", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(ClientActivity.this, "开始游戏", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(ClientActivity.this, GameView.class);
                    intent.putExtra("selfPukes",selfPukes);
                    intent.putExtra("threePukes",threePukes);
                    intent.putExtra("allUserName",userNames);
                    intent.putExtra("selfNameIndex",getSelfNameIndex(msg.obj.toString()));
                    startActivity(intent);
                    finish();
                    break;
                case 3:
                    Toast.makeText(ClientActivity.this, "人数不足三人", Toast.LENGTH_SHORT).show();
                    connect.setText("取消连接");
                    user_name.setCursorVisible(false);
                    user_name.setFocusable(false);
                    user_name.setFocusableInTouchMode(false);
                    break;
                case 4:
                    String s = msg.obj.toString();
                    switch (s.charAt(0)) {
                        case 's':
                            //初始化自身手牌
                            selfPukes = Utils.StringToArrayInt(s.substring(1));
                            break;
                        case 't':
                            //初始化地主牌
                            threePukes = Utils.StringToArrayInt(s.substring(1));
                            break;
                        case 'u':
                            //获取玩家信息
                            userNames = s.substring(1).split("--");
                            //模拟数据
//                            userNames = new String[]{"张三", "李四", "王五"};
                            break;
                    }
                    break;
                case 5:
                    Toast.makeText(ClientActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();
                    break;
            }

            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clinet);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        show.setText(ApplicationUtil.ADDRESS);
    }

    /**
     * 获得玩家名所在下标
     * @param selfName
     * @return
     */
    private int getSelfNameIndex(String selfName){
        for(int i=0;i<userNames.length;i++){
            if(userNames[i].equals(selfName)){
                return i;
            }
        }
        return -1;
    }

    @OnClick(R.id.client_connect)
    public void startConnect(View v) {
        //用户名不为空
        if(user_name.getText().toString().equals("")){
            handler.sendEmptyMessage(5);
            return;
        }
        String s = connect.getText().toString();
        //判断连接状态
        if (s.equals("取消连接")) {
            connect.setText("连接");
            user_name.setCursorVisible(true);
            user_name.setFocusable(true);
            user_name.setFocusableInTouchMode(true);
            ((ApplicationUtil) getApplication()).closeSocket();
            return;
        }
        //服务器地址不为空
        String address = show.getText().toString().trim();
        if (address.equals("")) {
            return;
        }
        //连接服务器
        ApplicationUtil.ADDRESS = address;
        final ApplicationUtil applicationUtil = (ApplicationUtil) getApplication();
        applicationUtil.init();
        //判断是否可以进入游戏
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        //是否已经连接
                        if (applicationUtil.isConnect()) {
                            //向服务器发送询问信息和自身用户名
                            String canPlay;
                            Socket socket = applicationUtil.getSocket();
                            OutputStream outputStream = socket.getOutputStream();
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            outputStream.write(("可以游戏"  + "\r\n").getBytes("utf-8"));
                            outputStream.write(("userName:"+ user_name.getText().toString().trim() + "\r\n").getBytes("utf-8"));
                            //
                            while (!applicationUtil.isCanPlay()) {
                                if ((canPlay = bufferedReader.readLine()) != null) {
                                    switch (canPlay) {
                                        case "YES":
                                            applicationUtil.setCanPlay(true);
                                            break;
                                        case "NO":
                                            applicationUtil.setCanPlay(false);
                                            handler.sendEmptyMessage(3);
                                            break;
                                        default:
                                            //初始化数据
                                            Message message = new Message();
                                            message.what = 4;
                                            message.obj = canPlay;
                                            handler.sendMessage(message);
                                            break;
                                    }
                                }
                            }
                            Log.i(TAG, "开始游戏");
                            //开始游戏 自身用户名
                            Message message = new Message();
                            message.what = 2;
                            message.obj = user_name.getText().toString().trim();
                            handler.sendMessage(message);
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}


